﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class report_Default : System.Web.UI.Page
{
    private Random random;
    private SqlConnection myConnection;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            myConnection = new SqlConnection(connString);
            random = new Random((int)DateTime.Now.Ticks);
            ViewImportResult();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message + "<br /><br />" + ex.StackTrace);
        }
    }

    private void FindFolder(string folderPaths)
    {
        folderPaths = Path.Combine( Server.MapPath("/"), folderPaths);
        string[] childfolderPaths = Directory.GetDirectories(folderPaths);
        foreach (string localFolder in childfolderPaths)
        {
            string[] files = Directory.GetFiles(localFolder);
            if (files.Length > 1)
            {
                ImportData(localFolder);
            }
            else
            {
                FindFolder(localFolder);
            }
        }
    }

    private void ViewImportResult()
    {
        myConnection.Open();
        string sql = "SELECT * FROM Patient order by ID desc";

        SqlCommand myCommand = new SqlCommand(sql, myConnection);

        DataSet myDataSet = new DataSet();

        SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
        myAdapter.Fill(myDataSet);

        GridView2.DataSource = myDataSet;
        GridView2.DataBind();

        myConnection.Close();
    }


    private string RandomString(int size)
    {
        StringBuilder builder = new StringBuilder();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        return builder.ToString();
    }

    private void ImportData(string localFolder)
    {
        string[] paths = localFolder.Split(new char[] { '\\' });
        string[] names = paths[paths.Length - 1].Split(new char[] { '-' });
        string code = names[0].Trim();
        string patientName = names[1].Trim();
        string companyName = paths[paths.Length - 2];
        myConnection.Open();
        //Kiểm tra tồn tại localFoder trong CSDL chưa
        string sql = "SELECT * FROM Patient where FolderPath = '" + localFolder + "'";
        SqlCommand myCommand = new SqlCommand(sql, myConnection);
        SqlDataReader dr = myCommand.ExecuteReader();
        if (!dr.HasRows)
        {
            dr.Close();
            string insertSql = string.Format("insert into Patient (Code, PatientName, CompanyName, Pass, FolderPath) values (N\'{0}\',N\'{1}\',N\'{2}\',N\'{3}\',N\'{4}\')", code, patientName, companyName, RandomString(5), localFolder);
            myCommand = new SqlCommand(insertSql, myConnection);
            myCommand.ExecuteNonQuery();
        }
        myConnection.Close();
    }

    protected void btnImportPatientData_Click(object sender, EventArgs e)
    {
        try
        {
            string currDateFolder = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString();
            string rootFolder = "report\\results\\" + currDateFolder;
            FindFolder(rootFolder);
            ViewImportResult();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message + "<br /><br />" + ex.StackTrace);
        }
    }
    protected void btnCreateTable_Click(object sender, EventArgs e)
    {
        try
        {
            string insertSql = "CREATE TABLE [dbo].[Patient]([ID] [int] IDENTITY(1,1) NOT NULL,[Code] [nvarchar](10) NULL,[PatientName] [nvarchar](50) NULL,[CompanyName] [nvarchar](100) NULL,[Pass] [nvarchar](10) NULL,[FolderPath] [nvarchar](max) NULL,CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED ([ID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]";
            SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
            myCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message + "<br /><br />" + ex.StackTrace);
        }
    }
    protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}
